App = {
  web3Provider: null,
  contracts: {},

  shopArray: [],  //购买的东西数组
  payedmoney: 0,  //花费的钱

  init: async function () {
    // Load shopmal.
    // $.getJSON('../platform.json', function (data) {
    //   var petsRow = $('#shopmal');
    //   var petTemplate = $('#shopTemplate');
    //   for (i = 0; i < data.length; i++) {
    //     petTemplate.find('.name').text(data[i].name);     
    //     petTemplate.find('.img').attr('src', data[i].picture);  
    //     petTemplate.find('.score').text(data[i].score);
    //     petTemplate.find('.to').attr('data-id', data[i].id);
    //     petsRow.append(petTemplate.html());
    //   }
    // });
    return await App.initWeb3();
  },

  initWeb3: async function () {
    // Modern dapp browsers...
    if (window.ethereum) {
      console.log('1')
      App.web3Provider = window.ethereum;
      try {
        // Request account access
        await window.ethereum.enable();
      } catch (error) {
        // User denied account access...
        console.error("User denied account access")
      }
    }
    // Legacy dapp browsers...
    else if (window.web3) {
      console.log('2')
      App.web3Provider = window.web3.currentProvider;
    }
    // If no injected web3 instance is detected, fall back to Ganache
    else {
      console.log('3')
      App.web3Provider = new Web3.providers.HttpProvider('http://127.0.0.1:8545');
    }
    web3 = new Web3(App.web3Provider);

    return App.initContract();
  },

  initContract: function () {
    // 加载Adoption.json，保存了Adoption的ABI（接口说明）信息及部署后的网络(地址)信息，它在编译合约的时候生成ABI，在部署的时候追加网络信息
    $.getJSON('Adoption.json', function (data) {
      // 用Adoption.json数据创建一个可交互的TruffleContract合约实例。
      App.contracts.Adoption = TruffleContract(data);

      // Set the provider for our contract
      App.contracts.Adoption.setProvider(App.web3Provider);

      App.contracts.Adoption.deployed().then(function(instance){
        App.adoptionInstance = instance;
        App.mymoney();
        // App.getmobile();
        // App.gettele();
        // App.getgong();
      })
      // Use our contract to retrieve and mark the adopted pets
      //return App.markAdopted();
    });
    return App.bindEvents();
  },

  bindEvents: function () {
    $(document).on('click', '.back', App.jump);
    $(document).on('click', '.paymoney', App.pay);
    $(document).on('click', '.to', App.jumpto);
  },

  mymoney: function () {
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      
      // 发送交易获取个人账户
      App.adoptionInstance.mymoney({ from: account }).then(function(mymoney) {
        console.log('-----===',mymoney)
        $('.mymoney').text(mymoney)
        App.getscore();   
         
      }).catch(function(err){
        console.log('mymoney',err)
      })
     
    });
  },

  getscore: function () {
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      App.adoptionInstance.getScoreLen({ from: accounts[0] }).then(function(len) {
        if(len > 0){
         
          App.geteach(len-1);
        }
      }).catch(function(err){
        console.log('getScoreLen',err)
      })

    })
  },

  geteach: function (index) {
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      App.adoptionInstance.getstore(index,{ from: account }).then(function(unicom) {
        console.log(unicom)
        if(unicom != ""){
          let unicomsum = 0
          unicom.split(",").forEach((item)=>{
            unicomsum = unicomsum + parseInt(item.split("-")[1])
          })
          var petsRow = $('#shopmal');
          var petTemplate = $('#shopTemplate'); 
          let name = "";
          let images = "";
          if(index == 0){
            name = "中国联通";
            images = "images/unicom.png";
          } 
          else if(index == 1){
            name = "中国移动";
            images = "images/mobile.png"
          } 
          else if(index == 2){
            name = "中国电信";
            images = "images/tele.png"
          }  
          else if(index == 3){
            name = "中国工商银行";
            images = "images/gongshang.png"
          }    
         
          petTemplate.find('.name').text(name);     
          petTemplate.find('.img').attr('src', images);  
          petTemplate.find('.score').text(unicomsum);
          petTemplate.find('.to').attr('data-id', index);
          petTemplate.find('.to').attr('data-refine', unicom);
          petTemplate.find('.to').attr('data-sum',unicomsum );
          petsRow.append(petTemplate.html());
        }
        if (index - 1 >= 0) {   
          App.geteach(index - 1);
        }
      }).catch(function(err){
        console.log('geteach',err)
      })
    })
    
  },

  gettele: function () {
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      App.adoptionInstance.gettele({ from: account }).then(function(unicom) {
        if(unicom == ""){
          return ;
        }
        let unicomsum = 0
        unicom.split(",").forEach((item)=>{
          console.log(item.split("-")[1])
          unicomsum = unicomsum + parseInt(item.split("-")[1])
        })
        var petsRow = $('#shopmal');
        var petTemplate = $('#shopTemplate');       
        petTemplate.find('.name').text('中国电信');     
        petTemplate.find('.img').attr('src', "images/tele.png");  
        petTemplate.find('.score').text(unicomsum);
        petTemplate.find('.to').attr('data-id', 2);
        petTemplate.find('.to').attr('data-refine', unicom);
        petTemplate.find('.to').attr('data-sum',unicomsum );
        petsRow.append(petTemplate.html());
      }).catch(function(err){
        console.log('gettele',err)
      })
    })
    
  },

  getgong: function () {
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      App.adoptionInstance.getgong({ from: account }).then(function(unicom) {
        if(unicom == ""){
          return ;
        }
        let unicomsum = 0
        unicom.split(",").forEach((item)=>{
          console.log(item.split("-")[1])
          unicomsum = unicomsum + parseInt(item.split("-")[1])
        })
        var petsRow = $('#shopmal');
        var petTemplate = $('#shopTemplate');       
        petTemplate.find('.name').text('中国工商银行');     
        petTemplate.find('.img').attr('src', "images/gongshang.png");  
        petTemplate.find('.score').text(unicomsum);
        petTemplate.find('.to').attr('data-id', 3);
        petTemplate.find('.to').attr('data-refine', unicom);
        petTemplate.find('.to').attr('data-sum',unicomsum );
        petsRow.append(petTemplate.html());
      }).catch(function(err){
        console.log('gettele',err)
      })
    })
    
  },

  pay: function () {
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      
      // 发送交易支付
      console.log(App.shopArray)
      let shopArray = App.shopArray
      App.adoptionInstance.pay(App.payedmoney,{ from: account }).then(function() {
        for (i = 0; i < shopArray.length; i++) { 
          App.adoptionInstance.buy(shopArray[i].id,shopArray[i].amount,account,{from:account}).then(function() {
            window.location.href="order.html";
          }).catch(function(err){
            console.log('pay',err)
          })
        }
        
      }).catch(function(err){
        console.log('pay',err)
      })
     
    });
  },

  markAdopted: function (adopters, account) {
    var adoptionInstance;

    App.contracts.Adoption.deployed().then(function (instance) {
      adoptionInstance = instance;

      // 调用合约的getAdopters(), 用call读取信息不用消耗gas
      return adoptionInstance.getAdopters.call();
    }).then(function (adopters) {
      for (i = 0; i < adopters.length; i++) {
        if (adopters[i] !== '0x0000000000000000000000000000000000000000') {
          $('.panel-pet').eq(i).find('button').text('Success').attr('disabled', true);
        }
      }
    }).catch(function (err) {
      console.log(err.message);
    });
  },

  getShopcars: function () {
    // 获取用户账号
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      
      // 发送交易添加购物车
      App.adoptionInstance.getShopcarsLen(account).then(function(len){
        if(len > 0){
           console.log(len)
          $('.account').text(len)
          $('.account').css("background-color","#ff5947");
          //App.loadShopcar(len-1);
        }
      }).catch(function(err){
        console.log('getshopcarlen',err)
      })
     
    });
  },

  addshop: function (event) {
    event.preventDefault();
    var shopId = parseInt($(event.target).data('id'));
    // 获取用户账号
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log('addshop',error);
      }
      var account = accounts[0];
      App.adoptionInstance.addshop(shopId, { from: account }).then(function(){
        return App.getShopcars();
      }).catch(function (err) {
        console.log('addshoperr',err.message);
      });
    });
  },

  loadShopcar: function(index) {
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      App.adoptionInstance.shopcars(account, index).then(function(shopid) {        
        if (index - 1 >= 0) {
         
          App.loadShopcar(index - 1);
        }
      }).catch(function(err) {
          console.log(err)
      });
    })

  },

  jump: function() {
    // window.open("https://tt.wo.cn/auth/attachment/downloadForMobile?id=8064");
    window.location.href="my.html";
  },

  jumpto: function(event) {
    event.preventDefault();
    let id = parseInt($(event.target).data('id'));
    let refine = $(event.target).data('refine');
    let sum = parseInt($(event.target).data('sum'));
    console.log(refine)
    console.log(id)
    console.log(sum)
    let url = `exchange.html?id=${id}&refine=${refine}&sum=${sum}`
    window.location.href=encodeURI(url);
  }

};

$(function () {
  $(window).on('load',function () {
    App.init();
  });
});

